Skip to content

assert_rules

Key Rules.

Attributes⚓︎

Classes⚓︎

AssertRule ⚓︎

Bases: BaseModel

Key Rule.

Source code in pytest_cache_assert/_check_assert/assert_rules.py
class AssertRule(BaseModel):
    """Key Rule."""

    pattern: Union[str, Pattern]  # type: ignore[type-arg] # https://github.com/pydantic/pydantic/issues/2636
    func: Callable[[T_DIFF, T_DIFF], bool]

    @classmethod
    def build_re(cls, pattern: List[str], func: Callable[[T_DIFF, T_DIFF], bool]) -> 'AssertRule':
        """Build a regex pattern from list."""
        if not pattern:
            raise ValueError("Expected at least one item in 'pattern'")
        if pattern[0].startswith('root['):
            raise ValueError("Exclude 'root' and brackets. This method builds it for you")
        pattern_re = f'root{_PAT_START}{_PAT_JOIN.join(pattern)}{_PAT_END}'
        return cls(pattern=re.compile(pattern_re), func=func)

    def is_regex(self) -> bool:
        """Helper for checking if pattern is a regex or string."""
        return not isinstance(self.pattern, str)

Functions⚓︎

build_re classmethod ⚓︎
build_re(pattern, func)

Build a regex pattern from list.

Source code in pytest_cache_assert/_check_assert/assert_rules.py
@classmethod
def build_re(cls, pattern: List[str], func: Callable[[T_DIFF, T_DIFF], bool]) -> 'AssertRule':
    """Build a regex pattern from list."""
    if not pattern:
        raise ValueError("Expected at least one item in 'pattern'")
    if pattern[0].startswith('root['):
        raise ValueError("Exclude 'root' and brackets. This method builds it for you")
    pattern_re = f'root{_PAT_START}{_PAT_JOIN.join(pattern)}{_PAT_END}'
    return cls(pattern=re.compile(pattern_re), func=func)
is_regex ⚓︎
is_regex()

Helper for checking if pattern is a regex or string.

Source code in pytest_cache_assert/_check_assert/assert_rules.py
def is_regex(self) -> bool:
    """Helper for checking if pattern is a regex or string."""
    return not isinstance(self.pattern, str)

Comparator ⚓︎

Bases: Enum

Comparator Enum for AssertRules.

Source code in pytest_cache_assert/_check_assert/assert_rules.py
class Comparator(Enum):  # noqa: H601
    """Comparator Enum for AssertRules."""

    LTE = 'new - old <= value'
    GTE = 'new - old >= value'
    WITHIN = 'abs(new - old) <= value'

Wild ⚓︎

AssertRule Wildcard Patterns.

Source code in pytest_cache_assert/_check_assert/assert_rules.py
class Wild:  # noqa: PIE798
    """AssertRule Wildcard Patterns."""

    @classmethod
    def build(cls, inner_pattern: str, count: int = 1) -> str:
        """Specify a custom regular expression to match nested keys."""
        if count < 1:
            raise ValueError('Count must be at least one')
        return _PAT_JOIN.join([inner_pattern] * count)

    @classmethod
    def index(cls, count: int = 1) -> str:
        """Return pattern that matches a specific number of nested lists in the cached data."""
        return cls.build(r'\d+', count)

    @classmethod
    def keys(cls, count: int = 1) -> str:
        """Return pattern that matches a specific number of nested dictionary keys."""
        return cls.build(r'[^\]]+', count)

    @classmethod
    def recur(cls, count: int = 1) -> str:
        """Return pattern that matches any level of nested dictionary keys or lists indices."""
        return cls.build(r'.+', count)

Functions⚓︎

build classmethod ⚓︎
build(inner_pattern, count=1)

Specify a custom regular expression to match nested keys.

Source code in pytest_cache_assert/_check_assert/assert_rules.py
@classmethod
def build(cls, inner_pattern: str, count: int = 1) -> str:
    """Specify a custom regular expression to match nested keys."""
    if count < 1:
        raise ValueError('Count must be at least one')
    return _PAT_JOIN.join([inner_pattern] * count)
index classmethod ⚓︎
index(count=1)

Return pattern that matches a specific number of nested lists in the cached data.

Source code in pytest_cache_assert/_check_assert/assert_rules.py
@classmethod
def index(cls, count: int = 1) -> str:
    """Return pattern that matches a specific number of nested lists in the cached data."""
    return cls.build(r'\d+', count)
keys classmethod ⚓︎
keys(count=1)

Return pattern that matches a specific number of nested dictionary keys.

Source code in pytest_cache_assert/_check_assert/assert_rules.py
@classmethod
def keys(cls, count: int = 1) -> str:
    """Return pattern that matches a specific number of nested dictionary keys."""
    return cls.build(r'[^\]]+', count)
recur classmethod ⚓︎
recur(count=1)

Return pattern that matches any level of nested dictionary keys or lists indices.

Source code in pytest_cache_assert/_check_assert/assert_rules.py
@classmethod
def recur(cls, count: int = 1) -> str:
    """Return pattern that matches any level of nested dictionary keys or lists indices."""
    return cls.build(r'.+', count)

Functions⚓︎

check_exact ⚓︎

check_exact(old, new)

Check for value equality.

PARAMETER DESCRIPTION
old

the old value

TYPE: T_DIFF

new

the new value

TYPE: T_DIFF

RETURNS DESCRIPTION
bool

True if both values are the exact same

TYPE: bool

Source code in pytest_cache_assert/_check_assert/assert_rules.py
@beartype
def check_exact(old: T_DIFF, new: T_DIFF) -> bool:
    """Check for value equality.

    Args:
        old: the old value
        new: the new value

    Returns:
        bool: True if both values are the exact same

    """
    return old == new  # type: ignore[no-any-return]

check_suppress ⚓︎

check_suppress(old, new)

Return True to suppress differences.

PARAMETER DESCRIPTION
old

the old value

TYPE: T_DIFF

new

the new value

TYPE: T_DIFF

RETURNS DESCRIPTION
bool

Always True

TYPE: bool

Source code in pytest_cache_assert/_check_assert/assert_rules.py
@beartype
def check_suppress(old: T_DIFF, new: T_DIFF) -> bool:  # noqa: ARG001
    """Return True to suppress differences.

    Args:
        old: the old value
        new: the new value

    Returns:
        bool: Always True

    """
    return True

check_type ⚓︎

check_type(old, new)

Check if both values are the exact same or same non-string type. Will attempt conversion from string.

PARAMETER DESCRIPTION
old

the old value

TYPE: T_DIFF

new

the new value

TYPE: T_DIFF

RETURNS DESCRIPTION
bool

True if both values are the same kind

TYPE: bool

Source code in pytest_cache_assert/_check_assert/assert_rules.py
@beartype
def check_type(old: T_DIFF, new: T_DIFF) -> bool:
    """Check if both values are the exact same or same non-string type. Will attempt conversion from string.

    Args:
        old: the old value
        new: the new value

    Returns:
        bool: True if both values are the same kind

    """
    if (
        check_exact(old=old, new=new)  # Catches if both null, etc.
        or (not isinstance(old, str) and isinstance(old, type(new)))
    ):
        return True

    return _try_type_coercion(old=old, new=new)

gen_check_date_proximity ⚓︎

gen_check_date_proximity(time_delta, comparator=Comparator.WITHIN)

Generate a AssertRule check for date within the specified range.

PARAMETER DESCRIPTION
time_delta

timedelta to use for checking that the new data is

TYPE: timedelta

comparator

defaults to Comparator.WITHIN. Can make directional by setting LTE or GTE

TYPE: Comparator DEFAULT: Comparator.WITHIN

RETURNS DESCRIPTION
Callable[[T_DIFF, T_DIFF], bool]

Callable[[T_DIFF, T_DIFF], bool]: AssertRule check

Source code in pytest_cache_assert/_check_assert/assert_rules.py
@beartype
def gen_check_date_proximity(
    time_delta: timedelta, comparator: Comparator = Comparator.WITHIN,
) -> Callable[[T_DIFF, T_DIFF], bool]:
    """Generate a AssertRule check for date within the specified range.

    Args:
        time_delta: timedelta to use for checking that the new data is
        comparator: defaults to Comparator.WITHIN. Can make directional by setting LTE or GTE

    Returns:
        Callable[[T_DIFF, T_DIFF], bool]: AssertRule check

    """
    return partial(_check_date_proximity, time_delta=time_delta, comparator=comparator)

gen_check_date_range ⚓︎

gen_check_date_range(min_date=None, max_date=None)

Generate a AssertRule check for date within the specified range.

PARAMETER DESCRIPTION
min_date

optional minimum datetime

TYPE: Optional[datetime] DEFAULT: None

max_date

optional maximum datetime

TYPE: Optional[datetime] DEFAULT: None

RETURNS DESCRIPTION
Callable[[T_DIFF, T_DIFF], bool]

Callable[[T_DIFF, T_DIFF], bool]: AssertRule check

Source code in pytest_cache_assert/_check_assert/assert_rules.py
@beartype
def gen_check_date_range(
    min_date: Optional[datetime] = None, max_date: Optional[datetime] = None,
) -> Callable[[T_DIFF, T_DIFF], bool]:
    """Generate a AssertRule check for date within the specified range.

    Args:
        min_date: optional minimum datetime
        max_date: optional maximum datetime

    Returns:
        Callable[[T_DIFF, T_DIFF], bool]: AssertRule check

    """
    return partial(_check_date_range, min_date=min_date, max_date=max_date)

Last update: August 30, 2023
Created: August 30, 2023